<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/employees/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="hProexcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{row}">
              <img v-if="row.staffPhoto" class="avatar" :src="row.staffPhoto" alt="">
              <ImageHolder v-else :src="row.staffPhoto" class="avatar" />
              <!-- <img v-else src="~@/assets/common/bigUserHeader.png" class="avatar" alt=""> -->
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />

          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              {{ formOfEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template v-slot="{row}">
              {{ formDate(row.timeOfEntry) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <!-- <el-button
                type="text"
                size="small"
                @click="$router.push({
                  path:'/employees/detail',
                  query:{id:row.id}
                })"
              >查看</el-button> -->
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hRoles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="q.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      title="添加员工"
      :visible.sync="showDialog"
      width="35%"
      :close-on-perss-escape="false"
      :close-on-click-modal="false"
      @closed="hClosed"
    >
      <!-- <employ-dialog v-if="showDialog" @success="hSuccess" @close="showDialog=false" /> -->
      <employ-dialog ref="resetForm" @success="hSuccess" @close="showDialog=false" />
    </el-dialog>

    <el-dialog
      title="添加员工"
      :visible.sync="showDialogRole"
      width="35%"
      :close-on-perss-escape="false"
      :close-on-click-modal="false"
    >
      <AssignRole :id="curId" />
    </el-dialog>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import employDialog from '@/views/employees/employDialog.vue'
import employees from '@/constant/employees'
import { delEmployee, getSysUser } from '@/api/employees'
import AssignRole from '@/views/employees/assignRole.vue'

const hireTypeMap = {} // {1：正式 ，2：非正式}
employees.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})
export default {
  components: {
    employDialog,
    AssignRole
  },
  data() {
    return {
      curId: '',
      list: [],
      q: {
        page: 1,
        size: 5
      },
      total: 0,
      showDialog: false,
      showDialogRole: false
    }
  },
  created() {
    this.loadEmployees()
    // console.log(this.$route)
  },
  methods: {
    // 发送请求获取数据渲染页面
    async loadEmployees() {
      try {
        const res = await getSysUser(this.q)
        // console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (e) {
        console.log(e)
      }
    },
    // 设置聘用形式
    formOfEmployment(data) {
      // console.log(data)
      return hireTypeMap[data]
    },
    // 设置分页
    handleSizeChange(size) {
      this.q.size = size
      this.loadEmployees()
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.loadEmployees()
    },
    // 删除员工列表
    async hDel(id) {
      try {
        await this.$confirm('确认删除吗?', '提示', { type: 'warning' })
        const res = await delEmployee(id)
        // console.log(res)
        this.$message.success(res.message)
        // 判断当前页数组的长度 === 0 && 分页 > 1
        console.log(this.list)
        if (this.list.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.loadEmployees()
      } catch (e) {
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    hAdd() {
      this.showDialog = true
    },
    // 关闭Dialog
    hSuccess() {
      this.showDialog = false
      if (this.total % this.q.size === 0) {
        this.total++
      }
      // 跳转到最后一页
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployees()
    },
    hClosed() {
      this.$refs.resetForm.resetForm()
    },
    // 格式化时间
    formDate(date) {
      return dayjs(date).format('YYYY - DD - MM')
    },
    async hProexcel() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const res = await getSysUser({ page: 1, size: this.total })
      // console.log(res)
      const newList = res.data.rows
      // console.log(newList)
      const first = newList[0]
      if (!first) return
      const header = Object.keys(first).map(item => {
        return mapInfo[item]
      })
      // console.log(header)
      const data = newList.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = hireTypeMap[code]
        item['timeOfEntry'] = dayjs(item['timeOfEntry']).format('YYYY - DD - MM')
        item['correctionTime'] = dayjs(item['correctionTime']).format('YYYY - DD - MM')
        return Object.values(item)
      })
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: header,
          data: data,
          filename: '在职员工列表', // 导出文件名
          autoWidth: true, // 宽度自适应
          bookType: 'xlsx' // 导出文件类型
        })
      })
    },
    // 分配角色
    hRoles(id) {
      this.showDialogRole = true
      this.curId = id
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
</style>
